<?php
namespace app\common\logic;

use think\Db;
use think\Model;

class Tag extends Base
{
    // layui 颜色
    private  $colors = [
            '',
            'layui-bg-orange',
            'layui-bg-green',
            'layui-bg-cyan',
            'layui-bg-blue',
            'layui-bg-black',
            'layui-bg-gray',
        ];

    public function add($name)
    {
        Db::name('tag')->insert(['name'=>$name]);
    }

    // 获取标签通过文章id
    public function getTagsByArticleId($id)
    {
        $tag_id_arr = Db::name('article_tag')->where('article_id',$id)->column('tag_id');
        $tags = Db::name('tag')->column('name','id');
        $result = [];
        foreach ($tag_id_arr as $tag_id) {
            $result[$tag_id] = $tags[$tag_id];
        }
        return $result;
    }

    // 获取文章标签html通过文章id
    public function getTagsHtmlByArticleId($id)
    {
        $tags = $this->getTagsByArticleId($id);
        $result = '';
        $i = 0;
        foreach ($tags as $id => $name) {
            $result .= "                            <a href='/index/article/tag/{$id}' class='layui-badge {$this->colors[($i%7)]}'>{$name}</a>\r\n";
            $i++;
        }
        return $result;
    }

    // 获取某个标签的所有文章id数组
    public function getArticleIdsByTagId($id)
    {
        $rt = Db::name('article_tag')->where('tag_id', $id)->column('article_id');
        return $rt;
    }

    // 热门标签列表
    public function getHotTag()
    {
        $rt = Db::name('article_tag')->field('*,count(tag_id) as num')->join('tag','id = tag_id')->order('num desc,id desc')->group('tag_id')->select();
        foreach ($rt as &$item) {
            $item['url'] = '/index/article/tag/'.$item['id'];
        }
        return $rt;
    }

    // 热门标签html代码
    public function getHotTagHtml()
    {
        $list = $this->getHotTag();
        $rt = '';
        foreach ($list as $key => $item) {
            $rt .= "						<a href='{$item['link']}' class='layui-badge {$this->colors[$key%7]}'>{$item['name']}({$item['num']})</a>\r\n";
        }
        return $rt;
    }

    /**
     * 添加文章标签关联数据，可能要添加标签
     * @param $pm
     */
    public function addArticleTagMaybeAddTag($pm)
    {
        if (is_string($pm['tag'])) {
            $pm['tag'] = explode(',', $pm['tag']);
        }
        foreach ($pm['tag'] as $tag) {
            if (ctype_digit((string)$tag)) {
                Db::name('article_tag')->insert(['tag_id'=>$tag,'article_id'=>$pm['article_id']]);
            } else {
                $tag_id = Db::name('tag')->insertGetId(['name'=>$tag]);
                Db::name('article_tag')->insert(['tag_id'=>$tag_id,'article_id'=>$pm['article_id']]);
            }
        }
    }






}